import ROSLIB from "roslib";
import { cmd_vel_listener } from "./topic";

// 键盘控制控制的线速度和角速度，初始值与手柄模块相同
var ml = 0.3; // m/s
var ma = 0.4; // rad/s

/**
 * 接收速度参数创建指令对象，并由cmd_vel_listener主题节点发布该移动指令
 * @param {number} linear 线速度
 * @param {number} angular 角速度
 */
function move(linear, angular) {
  if (linear == 0 && angular == 0) {
    // console.log("stop");
  }
  var twist = new ROSLIB.Message({
    linear: {
      x: linear,
      y: 0,
      z: 0,
    },
    angular: {
      x: 0,
      y: 0,
      z: angular,
    },
  });
  // console.log(linear);
  cmd_vel_listener.publish(twist);
}

/**
 * 接收的键盘符号并做出反应
 * @param {number} e 键盘符号
 */
function moveByKeyboard(e) {
  console.log("keyCode" + e.keyCode);
  var key = [
    73, // up
    85, // up-left
    79, // up-right
    188, // dowm
    77, // dowm-left
    190, // dowm-right
    74, // left
    76, // right
    75 // stop
  ];
  if (key.includes(e.keyCode)) {
    switch (e.keyCode) {
      case 73:
        move(ml, 0);
        break;
      case 188:
        move(-ml, 0);
        break;
      case 74:
        move(0, ma);
        break;
      case 76:
        move(0, -ma);
        break;
      case 75:
        move(0, 0);
        break;
      //
      case 85:
        move(ml, ma);
        break;
      case 79:
        move(ml, -ma);
        break;
      case 77:
        move(-ml, ma);
        break;
      case 190:
        move(-ml, -ma);
        break;

      default:
        break;
    }
  }
};
/**
 * 发布停止命令
 */
function stop() {
  move(0, 0);
}
/**
 * 设置线速度
 * @param {number} newValue 
 */
function setKBMaxLinear(newValue) {
  ml = newValue;
  console.log("setKBMaxLinear:" + newValue);
}

/**
 * 设置角速度
 * @param {number} newValue 
 */
function setKBMaxAngular(newValue) {
  ma = newValue;
  console.log("setKBMaxAngular:" + newValue);
}

/**
 * 在目标元素上添加键盘监听
 * @param {object} element 目标元素
 */
function createKeyboardListener(element) {
  element.addEventListener("keydown", moveByKeyboard);
  element.addEventListener("keyup", stop);
}

/**
 * 在目标元素上删除键盘监听
 * @param {object} element 目标元素
 */
function destroyKeyboardListener(element) {
  element.removeEventListener("keydown", moveByKeyboard);
  element.removeEventListener("keyup", stop);
}

export { moveByKeyboard, createKeyboardListener, destroyKeyboardListener, setKBMaxLinear, setKBMaxAngular };